<template>
  <div class="container">
    <div class="login_box">
      <div class="avatar">
        <img src="../assets/logo.png" alt="">
      </div>
      <div class="login_form">
        <el-form :model="loginModel" :rules="loginModelRule" ref="loginFormRef">
          <el-form-item prop="username">
            <el-input v-model="loginModel.username" placeholder="请输入用户名">
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="loginModel.password" placeholder="请输入密码">
              <i slot="prefix" class="el-input__icon el-icon-lock"></i>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="btn_box">
          <el-button type="primary" @click="login">
            登录
          </el-button>
          <el-button @click="reset">重置
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //form绑定的表单对象
      loginModel: {
        username: '',
        password: '',
      },
      //验证规则
      loginModelRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    login() {
      //预验证
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return
        //发送登录请求
        const res = await this.$http.post('user/login', this.loginModel)
        if (!res.flag) return this.$message.error(res.msg)
        this.$message.success('登录成功')
        //登录成功后
        //保存token到sessionStorage中
        window.sessionStorage.setItem('token', res.data.token)
        //跳转到首页
        this.$router.push('/home')
      })
    },
    reset() {
      this.$refs.loginFormRef.resetFields()
    },
  },
}
</script>

<style scoped lang="less">
.container {
  height: 100%;
  background-color: #2b4b6b;
  .login_box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 300px;
    background-color: #fff;
    border-radius: 5px;
    .avatar {
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      height: 130px;
      width: 130px;
      border-radius: 50%;
      overflow: hidden;
      border: 1px solid #eee;
      background-color: #fff;
      padding: 10px;
      box-shadow: 0 0 10px #ddd;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
  }
}
.login_form {
  margin-top: 100px;
  padding: 0 20px;
}
.btn_box {
  text-align: right;
}
</style>
